package com.forum.common;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.forum.entity.Result1;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 阿里云 OSS 工具类
 */
@Component  //将工具类交给ioc容器管理，这样使用的时候不需要new对象了，直接autowired注入就能使用
public class AliOSSUtils {

    //配置访问凭证
    private String endpoint = "https://oss-cn-guangzhou.aliyuncs.com";  //地域节点
    private String accessKeyId = "LTAI5tLffaCe1QKX1QzxVyzp";
    private String accessKeySecret = "nBQu6cpyleuheqswDWjJIKhbhT7VHe";
    private String bucketName = "codetudy";  //填写Bucket名称,存储空间

    /**
     * 实现上传图片到OSS
     */
    public String upload(MultipartFile file) throws IOException {
        // 获取上传的文件的输入流
        InputStream inputStream = file.getInputStream();

        // 避免文件覆盖,生成uuid作为文件名
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);

        //文件访问路径
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
        // 关闭ossClient
        ossClient.shutdown();
        return url;// 把上传到oss的路径返回
    }

    public Result1 del(String filename) throws IOException {
        //删除文件
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.deleteObject("codetudy", filename);

        // 关闭ossClient
        ossClient.shutdown();
        return Result1.success("删除文件成功");
    }

}
